// get的基础自定义
import { HOST } from "./HOST";
import { message } from "antd";
import { JsonConvert, OperationMode, ValueCheckingMode } from "json2typescript"; // json转ts对象库
// import vue from 'vue'
import qs from "qs"; // 请求参数处理库
import axios from "axios"; // 请求库
import { ResponseData, ResponseModel } from "../models/common/resPonse";
let jsonConvert: JsonConvert = new JsonConvert();
export class MyHttp {
  loadingdelay: number = 2500; // 加载效果延迟显示时间
  isShowAjaxChildEff: boolean = true; // 是否显示子项ajax效果
  constructor() {
    axios.defaults.headers.post["Content-Type"] =
      "application/x-www-form-urlencoded"; // 请求头
    axios.defaults.baseURL = HOST; // url公共前缀
    jsonConvert.operationMode = OperationMode.LOGGING; // json转换打印debug信息
    jsonConvert.ignorePrimitiveChecks = false; // json转换禁止数字赋值给字符串
    jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; // json转换不允许为空
  }
  setHost(HOST: string) {
    axios.defaults.baseURL = HOST; // url公共前缀
  }
  getHost() {
    return axios.defaults.baseURL; // url公共前缀
  }
  resProcessing(res: ResponseModel) {
    // 自定义业务返回信息判断
    let data = res.data;
    if (res.code === -1) {
      message.error({
        content: res.mes,
        duration: 2000,
      });
    }
  }
  resArryProcessing(resArry: ResponseModel[]) {
    // 自定义业务返回信息数组判断
    let errMes: string | undefined; // 业务异常信息
    resArry.forEach((item, index) => {
      if (item.code === -1) {
        if (index > 0) {
          errMes += "/n";
        }
        errMes += item.mes;
      }
    });
    if (errMes) {
      message.error({
        content: errMes,
        duration: 2000,
      });
    }
  }
  errProcessing(err: any) {
    // 异常处理函数
    // console.info('错误', err)
    if (err.status === 500) {
      message.error({
        content: "请求失败请检查网络",
        duration: 2000,
      });
    } else {
      message.error({
        content: "请求失败没返回",
        duration: 2000,
      });
    }
  }
  get<T>(
    url: string,
    classObject: new () => T,
    info: object = {},
    isShowLoading: boolean = true,
    isDisposeRes: boolean = true
  ): Promise<ResponseData<T>> {
    // get请求
    return new Promise((resolve, reject) => {
      let delay: NodeJS.Timeout;
      if (isShowLoading && this.isShowAjaxChildEff) {
        delay = setTimeout(
          message.loading({
            duration: 0, // 持续展示 toast
            // forbidClick: true, // 禁用背景点击
            // loadingType: "spinner",
            message: "",
          }),
          this.loadingdelay
        );
      }
      // get请求
      axios
        .get<T>(url, {
          params: info,
        })
        .then((res) => {
          let responseData: ResponseData<T>; // 服务端返回数据
          responseData = jsonConvert.deserializeObject(res.data, ResponseModel); // json转T类型对象
          if (responseData.data) {
            responseData.data = jsonConvert.deserializeObject(
              responseData.data,
              classObject
            ); // json转T类型对象
          } else {
            responseData.data = new classObject();
          }

          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            clearTimeout(delay);
          
          }
          resolve(responseData);
        })
        .catch((err) => {
          if (isShowLoading && this.isShowAjaxChildEff) {
            clearTimeout(delay);
       
          }
          this.errProcessing(err); // 错误处理
          reject(err);
        });
    });
  }
  post<T>(
    url: string,
    classObject: new () => T,
    info: object = {},
    isShowLoading: boolean = true,
    isDisposeRes: boolean = true
  ): Promise<ResponseData<T>> {
    // post请求
    return new Promise((resolve, reject) => {
      let delay: NodeJS.Timeout;
      if (isShowLoading && this.isShowAjaxChildEff) {
        delay = setTimeout(
          message.loading({
            duration: 0, // 持续展示 toast
            // forbidClick: true, // 禁用背景点击
            // loadingType: "spinner",
            message: "",
          }),
          this.loadingdelay
        );
      }

      // get请求
      axios
        .post<T>(url, qs.stringify(info), {
          // qs序列化参数 做成stringformdate格式
          headers: {
            // 头部配置
            Accept: "application/json, text/javascript, */*; q=0.01",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
          },
          // params: info,
          // paramsSerializer: function(params) {
          //     return Qs.stringify(params, { arrayFormat: 'brackets' })
          // },
        })
        .then((res) => {
          let responseData: ResponseData<T>; // 服务端返回数据
          responseData = jsonConvert.deserializeObject(res.data, ResponseModel); // json转T类型对象
          if (responseData.data) {
            responseData.data = jsonConvert.deserializeObject(
              responseData.data,
              classObject
            ); // json转T类型对象
          } else {
            responseData.data = new classObject();
          }

          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            clearTimeout(delay);
      
          }
          resolve(responseData);
        })
        .catch((err) => {
          if (isShowLoading && this.isShowAjaxChildEff) {
            clearTimeout(delay);
          
          }
          this.errProcessing(err);
          reject(err);
        });
    });
  }
  formAjax<T>(
    url: string,
    classObject: new () => T,
    formData: FormData,
    isShowLoading: boolean = true,
    isDisposeRes: boolean = true
  ): Promise<ResponseData<T>> {
    return new Promise((resolve, reject) => {
      let delay: NodeJS.Timeout;
      if (isShowLoading && this.isShowAjaxChildEff) {
        delay = setTimeout(
          message.loading({
            duration: 0, // 持续展示 toast
            // forbidClick: true, // 禁用背景点击
            // loadingType: "spinner",
            message: "",
          }),
          this.loadingdelay
        );
      }

      // get请求
      axios
        .post<ResponseModel>(url, formData, {
          // qs序列化参数 做成stringformdate格式
          headers: {
            // 头部配置
            "Content-Type": "multipart/form-data",
          },

          // params: info,
          // paramsSerializer: function(params) {
          //     return Qs.stringify(params, { arrayFormat: 'brackets' })
          // },
        })
        .then((res) => {
          let responseData: ResponseData<T>; // 服务端返回数据
          responseData = jsonConvert.deserializeObject(res.data, ResponseModel); // json转T类型对象
          if (responseData.data) {
            responseData.data = jsonConvert.deserializeObject(
              responseData.data,
              classObject
            ); // json转T类型对象
          } else {
            responseData.data = new classObject();
          }

          if (isDisposeRes && this.isShowAjaxChildEff) {
            this.resProcessing(responseData);
          }
          if (isShowLoading && this.isShowAjaxChildEff) {
            clearTimeout(delay);
        
          }
          resolve(responseData);
        })
        .catch((err) => {
          if (isShowLoading && this.isShowAjaxChildEff) {
            clearTimeout(delay);
        
          }
          this.errProcessing(err);
          reject(err);
        });
    });
  }
  getmutidata(promiseArry: Array<Promise<any>>) {
    let delay: NodeJS.Timeout;
    this.isShowAjaxChildEff = false;
    delay = setTimeout(
      message.loading({
        duration: 0, // 持续展示 toast
        // forbidClick: true, // 禁用背景点击
        // loadingType: "spinner",
        message: "",
      }),
      this.loadingdelay
    );

    Promise.all(promiseArry)
      .then((resArry) => {
        console.log("请求成功返回", resArry);
        clearTimeout(delay);
 
      })
      .catch((errArry) => {
        console.log("请求成功返回", errArry);
        clearTimeout(delay);
     
      });
  }
}

export default new MyHttp();
